package com.hzy.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzy.common.exception.base.BaseException;
import com.hzy.common.utils.DateUtils;
import com.hzy.nursing.domain.*;
import com.hzy.nursing.dto.CheckInApplyDto;
import com.hzy.nursing.dto.CheckInContractDto;
import com.hzy.nursing.dto.CheckInElderDto;
import com.hzy.nursing.mapper.*;
import com.hzy.nursing.util.CodeGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzy.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-13
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;
    
    @Autowired
    private RoomMapper roomMapper;

    /**
     * 申请入住
     * @param checkInApplyDto
     */
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否入住，假如老人已经入住，提示：老人已入住  结束程序

        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据身份证号查询
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("老人已入住");
        }

        //检查床位是否已被占用（关键修复）
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        if (bed == null) {
            throw new BaseException("床位不存在");
        }
        if (bed.getBedStatus() == 1) {
            throw new BaseException("该床位已被占用，请选择其他床位");
        }
        
        //更新老人选择的床位状态为已占用
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //更新或新增老人
        elder = insertOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());

        //新增签约办理信息  合同
        //生成一个合同编号
        String contractNo = "HT"+CodeGenerator.generateContractNumber();
        insertContract(elder,contractNo,checkInApplyDto);

        //新增入住信息  check_in
        CheckIn checkIn = inserCheckIn(elder, bed, checkInApplyDto);

        //新增入住配置信息  check_in_config
        insertCheckInConfig(checkIn,checkInApplyDto);
    }

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 新增入住配置信息
     * @param checkIn
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        //属性拷贝
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param bed
     * @param checkInApplyDto
     * @return
     */
    private CheckIn inserCheckIn(Elder elder, Bed bed, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setBedId(bed.getId());
        checkIn.setElderId(elder.getId());
        checkIn.setStatus(0);  // 0=已入住, 1=已退住
        checkIn.setCreateTime(DateUtils.getNowDate());

        // 从配置中获取护理等级名称
        if(checkInApplyDto.getCheckInConfigDto() != null){
            checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        }

        // 从配置中获取入住日期范围
        if(checkInApplyDto.getCheckInConfigDto() != null){
            checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
            checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        }

        // 将家属信息序列化存储到 remark 字段
        if(checkInApplyDto.getElderFamilyDtoList() != null && !checkInApplyDto.getElderFamilyDtoList().isEmpty()){
            checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        }

        checkInMapper.insert(checkIn);
        return checkIn;
    }

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 新增签约办理信息  合同
     * @param elder
     * @param contractNo
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, String contractNo, CheckInApplyDto checkInApplyDto) {
        //新增签约办理信息  合同
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        contract.setContractNumber(contractNo);
        contract.setElderName(elder.getName());
        contract.setElderId(elder.getId());
        contract.setCreateTime(DateUtils.getNowDate());

        // 从配置中获取入住日期范围
        if(checkInApplyDto.getCheckInConfigDto() != null){
            contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
            contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        }

        contractMapper.insert(contract);
    }

    /**
     * 更新或新增老人
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        elder.setCreateTime(DateUtils.getNowDate());
        elderMapper.insert(elder);
        return elder;
    }

    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    @Override
    public int insertCheckIn(CheckIn checkIn) {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insertCheckIn(checkIn);
    }

    @Override
    public int updateCheckIn(CheckIn checkIn) {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateCheckIn(checkIn);
    }

    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteCheckInByIds(ids);
    }

    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteCheckInById(id);
    }

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Override
    public com.hzy.nursing.vo.CheckInDetailVo selectCheckInDetailById(Long id) {
        // 查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null) {
            throw new BaseException("入住信息不存在");
        }

        // 创建返回对象
        com.hzy.nursing.vo.CheckInDetailVo checkInVo = new com.hzy.nursing.vo.CheckInDetailVo();

        // 1. 查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if (elder != null) {
            com.hzy.nursing.vo.CheckInElderVo elderVo = new com.hzy.nursing.vo.CheckInElderVo();
            BeanUtils.copyProperties(elder, elderVo);
            // 注释掉自动计算年龄，保留用户输入的年龄值
            // 如果需要自动计算，应该在前端实现，而不是后端覆盖用户输入
            /*
            // 计算年龄（根据出生日期）
            if (elder.getBirthday() != null && !elder.getBirthday().isEmpty()) {
                try {
                    java.time.LocalDate birthDate = java.time.LocalDate.parse(elder.getBirthday());
                    java.time.LocalDate now = java.time.LocalDate.now();
                    int age = now.getYear() - birthDate.getYear();
                    if (now.getMonthValue() < birthDate.getMonthValue() || 
                        (now.getMonthValue() == birthDate.getMonthValue() && now.getDayOfMonth() < birthDate.getDayOfMonth())) {
                        age--;
                    }
                    elderVo.setAge(age);
                } catch (Exception e) {
                    // 日期解析失败，忽略
                }
            }
            */
            checkInVo.setCheckInElderVo(elderVo);
        }

        // 2. 查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configWrapper);
        if (checkInConfig != null) {
            com.hzy.nursing.vo.CheckInConfigVo configVo = new com.hzy.nursing.vo.CheckInConfigVo();
            BeanUtils.copyProperties(checkInConfig, configVo);
            
            // 添加床位相关信息（floorId, roomId, bedId）用于前端回显
            // 床位信息从 CheckIn 对象中获取，而不是从 CheckInConfig 中获取
            if (checkIn.getBedId() != null) {
                Bed bed = bedMapper.selectById(checkIn.getBedId());
                if (bed != null) {
                    configVo.setBedId(bed.getId());
                    configVo.setRoomId(bed.getRoomId());
                    
                    // 查询房间信息获取楼层ID
                    if (bed.getRoomId() != null) {
                        Room room = roomMapper.selectById(bed.getRoomId());
                        if (room != null) {
                            configVo.setFloorId(room.getFloorId());
                        }
                    }
                }
            }
            
            // 如果配置中没有开始和结束日期，从合同中获取
            if (configVo.getStartDate() == null || configVo.getEndDate() == null) {
                LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
                contractWrapper.eq(Contract::getElderId, checkIn.getElderId());
                contractWrapper.orderByDesc(Contract::getCreateTime);
                contractWrapper.last("LIMIT 1");
                Contract contract = contractMapper.selectOne(contractWrapper);
                if (contract != null) {
                    if (configVo.getStartDate() == null) {
                        configVo.setStartDate(contract.getStartDate());
                    }
                    if (configVo.getEndDate() == null) {
                        configVo.setEndDate(contract.getEndDate());
                    }
                }
            }
            
            checkInVo.setCheckInConfigVo(configVo);
        }

        // 3. 查询合同信息
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, checkIn.getElderId());
        contractWrapper.orderByDesc(Contract::getCreateTime);
        contractWrapper.last("LIMIT 1");
        Contract contract = contractMapper.selectOne(contractWrapper);
        if (contract != null) {
            checkInVo.setContract(contract);
        }

        // 4. 查询家属信息
        // 从check_in的remark字段反序列化家属信息
        if (checkIn.getRemark() != null && !checkIn.getRemark().isEmpty()) {
            try {
                List<com.hzy.nursing.vo.ElderFamilyVo> familyList = 
                    JSONUtil.toList(checkIn.getRemark(), com.hzy.nursing.vo.ElderFamilyVo.class);
                checkInVo.setElderFamilyVoList(familyList);
            } catch (Exception e) {
                // 如果反序列化失败，返回空列表
                checkInVo.setElderFamilyVoList(new java.util.ArrayList<>());
            }
        } else {
            // 如果没有家属信息，返回空列表
            checkInVo.setElderFamilyVoList(new java.util.ArrayList<>());
        }

        return checkInVo;
    }

    /**
     * 更新入住申请信息（用于编辑功能）
     * @param checkInApplyDto
     */
    @Override
    public void updateCheckInApply(CheckInApplyDto checkInApplyDto) {
        // 1. 更新老人信息
        CheckInElderDto elderDto = checkInApplyDto.getCheckInElderDto();
        if (elderDto != null && elderDto.getId() != null) {
            Elder elder = new Elder();
            BeanUtils.copyProperties(elderDto, elder);
            
            // 检查床位是否变更
            Elder existingElder = elderMapper.selectById(elderDto.getId());
            Long oldBedId = existingElder.getBedId();
            Long newBedId = checkInApplyDto.getCheckInConfigDto() != null ? 
                checkInApplyDto.getCheckInConfigDto().getBedId() : null;
            
            // 如果床位变更了
            if (newBedId != null && !newBedId.equals(oldBedId)) {
                // 检查新床位是否可用
                Bed newBed = bedMapper.selectById(newBedId);
                if (newBed == null) {
                    throw new BaseException("新床位不存在");
                }
                if (newBed.getBedStatus() == 1 && !newBedId.equals(oldBedId)) {
                    throw new BaseException("该床位已被占用，请选择其他床位");
                }
                
                // 释放旧床位
                if (oldBedId != null) {
                    Bed oldBed = bedMapper.selectById(oldBedId);
                    if (oldBed != null) {
                        oldBed.setBedStatus(0); // 设置为空闲
                        bedMapper.updateById(oldBed);
                    }
                }
                
                // 占用新床位
                newBed.setBedStatus(1);
                bedMapper.updateById(newBed);
                
                // 更新老人的床位信息
                elder.setBedNumber(newBed.getBedNumber());
                elder.setBedId(newBed.getId());
            }
            
            elderMapper.updateById(elder);
        }
        
        // 2. 更新入住配置
        if (checkInApplyDto.getCheckInConfigDto() != null && checkInApplyDto.getId() != null) {
            LambdaQueryWrapper<CheckInConfig> configWrapper = new LambdaQueryWrapper<>();
            configWrapper.eq(CheckInConfig::getCheckInId, checkInApplyDto.getId());
            CheckInConfig existingConfig = checkInConfigMapper.selectOne(configWrapper);
            
            if (existingConfig != null) {
                CheckInConfig checkInConfig = new CheckInConfig();
                BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
                checkInConfig.setId(existingConfig.getId());
                checkInConfig.setCheckInId(checkInApplyDto.getId());
                checkInConfigMapper.updateById(checkInConfig);
            }
        }
        
        // 3. 更新合同信息
        if (checkInApplyDto.getCheckInContractDto() != null && elderDto != null && elderDto.getId() != null) {
            LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
            contractWrapper.eq(Contract::getElderId, elderDto.getId());
            contractWrapper.orderByDesc(Contract::getCreateTime);
            contractWrapper.last("LIMIT 1");
            Contract existingContract = contractMapper.selectOne(contractWrapper);
            
            if (existingContract != null) {
                Contract contract = new Contract();
                BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
                contract.setId(existingContract.getId());
                contract.setElderId(elderDto.getId());
                
                // 更新合同的日期信息
                if (checkInApplyDto.getCheckInConfigDto() != null) {
                    contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
                    contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
                }
                contractMapper.updateById(contract);
            }
        }
        
        // 4. 更新入住记录中的家属信息（存在 remark 字段）
        if (checkInApplyDto.getId() != null) {
            CheckIn checkIn = getById(checkInApplyDto.getId());
            if (checkIn != null) {
                // 更新家属信息
                if (checkInApplyDto.getElderFamilyDtoList() != null) {
                    checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
                }
                
                // 更新入住记录的其他信息
                if (checkInApplyDto.getCheckInConfigDto() != null) {
                    checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
                    checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
                    checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
                }
                
                // 更新床位编号
                if (checkInApplyDto.getCheckInConfigDto() != null && 
                    checkInApplyDto.getCheckInConfigDto().getBedId() != null) {
                    Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
                    if (bed != null) {
                        checkIn.setBedNumber(bed.getBedNumber());
                        checkIn.setBedId(bed.getId());
                    }
                }
                
                updateById(checkIn);
            }
        }
    }
}
